package logic

import (
	"context"
	"fmt"
	"shopping/model/mysql"
	"shopping/model/redis"

	"shopping/userrpc/internal/svc"
	"shopping/userrpc/userrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *userrpc.LoginRequest) (*userrpc.LoginResponse, error) {
	// todo: add your logic here and delete this line
	get := redis.Rdb.Get("sendSmslogin" + in.Phone)
	if get.Val() != in.SendSms {
		return nil, fmt.Errorf("短信验证码错误")
	}
	var user mysql.Userr
	mysql.DB.Debug().Where("phone = ?", in.Phone).Find(&user)
	if user.Phone == "" {
		return nil, fmt.Errorf("账号未注册")
	}
	if user.Password != in.Password {
		return nil, fmt.Errorf("密码错误")
	}
	redis.Rdb.Del("sendSmslogin" + in.Phone)
	return &userrpc.LoginResponse{Id: int64(user.ID)}, nil
}
